package t856

import (
	"errors"
	"strconv"
	"strings"
)

type MyStack struct {
	items []string
}

func (m *MyStack) Push(n string) {
	m.items = append(m.items, n)
}

func (m *MyStack) Pop() (string, error) {
	if len(m.items) == 0 {
		return "", errors.New("empty of stack")
	}
	el := m.items[len(m.items)-1]
	m.items = m.items[:len(m.items)-1]
	return el, nil
}

func (m *MyStack) Top() (string, error) {
	if len(m.items) == 0 {
		return "", errors.New("empty of stack")
	}
	el := m.items[len(m.items)-1]
	return el, nil
}

func (m *MyStack) Size() int {
	return len(m.items)
}

func (m *MyStack) Empty() bool {
	if len(m.items) == 0 {
		return true
	}
	return false
}

func (m *MyStack) String() string {
	return strings.Join(m.items, " ")
}

func scoreOfParentheses(S string) int {
	stack := &MyStack{}

	sum := 0

	for _, i := range S {
		char := string(i)
		//fmt.Println(char)
		if char == ")" {
			cnt := 0
			for true {
				pop, err := stack.Pop()
				if err != nil {
					break
				}
				if pop == "(" {
					if cnt == 0 {
						stack.Push("1")
					} else {
						stack.Push(strconv.Itoa(cnt * 2))
					}
					cnt++
					break
				} else {
					n, _ := strconv.Atoi(pop)
					cnt += n
				}
			}
		} else {
			stack.Push(char)
		}
		//fmt.Println("stack : ", stack)
	}

	for {
		el, err := stack.Pop()
		if err != nil {
			break
		}
		num, _ := strconv.Atoi(el)
		sum += num
	}

	return sum
}
